package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Tang
 * @version 1.0
 * @date 2024/1/25 17:49
 */
@Slf4j
@Service
public class LearningServiceImpl implements LearningService {
    @Autowired
    MyCourseTableService myCourseTableService;
    @Autowired
    ContentServiceClient contentServiceClient;
    @Autowired
    MediaServiceClient mediaServiceClient;
    @Override
    public RestResponse<String> getvideo(String userId,
                                         Long courseId,
                                         Long teachplanId,
                                         String mediaId) {
        // 没有登录
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (Objects.isNull(coursepublish)) {
            return RestResponse.validfail("课程不存在");
        }
        // 远程调用课程计划获取试学资格
        if (StringUtils.isNoneEmpty(userId)) {
            // 获取学习资格
            XcCourseTablesDto learningState = myCourseTableService.getLearningState(userId, courseId);
            String learnStatus = learningState.getLearnStatus();
            // 没有选课或选课后未支付
            if ("702002".equals(learnStatus)) {
                return RestResponse.validfail("没有选课或选课后未支付");
            } else if ("702003".equals(learnStatus)) {
                return RestResponse.validfail("已过期请申请续期或重新支付");
            } else {
                return mediaServiceClient.getPlayUrlByMediaId(mediaId);
            }
        }
        // 查询课程收费规则
        String charge = coursepublish.getCharge();
        // 如果是免费的
        if ("201000".equals(charge)) {
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        return RestResponse.validfail("该课程没有选课");
    }
}
